package com.uzai.console.service.wechatprivate.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.WxqBlacklistTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.dto.wechatprivate.wxq.wxgroupblacklist.blacklistpub.WxqBlacklistPubIdDto;
import com.uzai.console.dto.wechatprivate.wxq.wxgroupblacklist.blacklistpub.WxqBlacklistPubQuery;
import com.uzai.console.entity.es.WxqBlacklistPub;
import com.uzai.console.entity.es.WxqBlacklistPubWhite;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.wechatprivate.WxqBlacklistPubService;
import com.uzai.console.vo.wechatprivate.wxq.wxgroupblacklist.blacklistpub.WxqBlacklistPubVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author liuqi
 * @date 2021年08月23日 20:25
 */
@Service
public class WxqBlacklistPubServiceImpl implements WxqBlacklistPubService {

    Logger logger = LoggerFactory.getLogger(WxqBlacklistPubServiceImpl.class);

    @Autowired
    private DeviceService deviceService;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;

    /**
     * 查询社群全网黑名单列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqBlacklistPubQuery
     * @return null
     */
    public Page<WxqBlacklistPubVo> findWxqBlacklistPubList(WxqBlacklistPubQuery wxqBlacklistPubQuery){
        //新建返回到页面的LIST对象
        List<WxqBlacklistPubVo> wxqBlacklistPubPageVoList = new ArrayList<>();
        //执行分页查询对象
        Page<WxqBlacklistPubVo> page = new Page<>();
        wxqBlacklistPubQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //黑名单类型(0打广告 1刷屏 2同行 3敏感词 4其他)
        if(wxqBlacklistPubQuery.getType() != null){
            boolQuery.must(QueryBuilders.termQuery("type", wxqBlacklistPubQuery.getType()));
        }

        //微信id
        if(StringUtils.isNotBlank(wxqBlacklistPubQuery.getWxid())){
            boolQuery.must(QueryBuilders.termQuery("wxid", wxqBlacklistPubQuery.getWxid()));
        }

        //微信昵称
        if(StringUtils.isNotBlank(wxqBlacklistPubQuery.getNick())){
            boolQuery.must(QueryBuilders.matchQuery("nick", wxqBlacklistPubQuery.getNick()));
        }

        //高亮字段
        String highlightField = null;

        searchSourceBuilder.query(boolQuery);

        //排序
        searchSourceBuilder.sort("createTime", SortOrder.DESC);

        ESResult esResult = elasticsearchUtil.searchListData(EsIndexName.UZAI_WXQ_BLACKLIST_PUB, searchSourceBuilder, wxqBlacklistPubQuery.getSize(), wxqBlacklistPubQuery.getFromIndex(), null, null, highlightField, null);
        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                WxqBlacklistPub wxqBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxqBlacklistPub.class);
                if(wxqBlacklistPub != null){
                    WxqBlacklistPubVo wxqBlacklistPubVo = new WxqBlacklistPubVo();
                    BeanUtils.copyProperties(wxqBlacklistPub, wxqBlacklistPubVo);

                    if(wxqBlacklistPubVo.getType() != null){
                        WxqBlacklistTypeEnum wxqBlacklistTypeEnum = WxqBlacklistTypeEnum.getById(wxqBlacklistPubVo.getType());
                        if(wxqBlacklistTypeEnum != null){
                            wxqBlacklistPubVo.setTypeName(wxqBlacklistTypeEnum.getDesc());
                        }
                    }


                    //是否加入白名单
                    String white_id = wxqBlacklistPubQuery.getMerId() + "_" + wxqBlacklistPub.getWxid();
                    Map<String,Object> map_white = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PUB_WHITE, white_id, null);
                    if(map_white == null){
                        wxqBlacklistPubVo.setWhiteStatus(0);  //未加入白名单
                    }else{
                        wxqBlacklistPubVo.setWhiteStatus(1);  //已经加入白名单
                    }

                    wxqBlacklistPubPageVoList.add(wxqBlacklistPubVo);
                }
            }
        }

        //返回到页面分页对象
        page.setRecords(wxqBlacklistPubPageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }

    /**
     * 加入社群白名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqBlacklistPubIdDto
     * @return null
     */
    @Transactional
    public void addWxqBlacklistPubWhite(WxqBlacklistPubIdDto wxqBlacklistPubIdDto){

        if(StringUtils.isBlank(wxqBlacklistPubIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PUB, wxqBlacklistPubIdDto.getId(), null);
        WxqBlacklistPub wxqBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WxqBlacklistPub.class);
        if(wxqBlacklistPub == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此全网黑名单不存在");
        }

        if(wxqBlacklistPub.getMerId().longValue() == wxqBlacklistPubIdDto.getMerId().longValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "不能将自己共享的全网黑名单加入到白名单当中");
        }

        String white_id = wxqBlacklistPubIdDto.getMerId() + "_" + wxqBlacklistPub.getWxid();
        Map<String,Object> white_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PUB_WHITE, white_id, null);
        WxqBlacklistPubWhite wxqBlacklistPubWhite  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(white_map)), WxqBlacklistPubWhite.class);
        if(wxqBlacklistPubWhite != null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此全网黑名单已经存在白名单列表中");
        }

        //加入白名称
        wxqBlacklistPubWhite = new WxqBlacklistPubWhite();
        BeanUtils.copyProperties(wxqBlacklistPub, wxqBlacklistPubWhite);
        wxqBlacklistPubWhite.setId(white_id);
        wxqBlacklistPubWhite.setMerId(wxqBlacklistPubIdDto.getMerId());
        Integer now = DateUtil.getNowTime();
        wxqBlacklistPubWhite.setCreateTime(now);
        wxqBlacklistPubWhite.setUpdateTime(now);
        //增加到全网黑名单
        elasticsearchUtil.addData(wxqBlacklistPubWhite, EsIndexName.UZAI_WXQ_BLACKLIST_PUB_WHITE, white_id);

        try {
            //延迟0.5秒
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }

    /**
     * 删除社群白名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqBlacklistPubIdDto
     * @return null
     */
    @Transactional
    public void deleteWxqBlacklistPubWhite(WxqBlacklistPubIdDto wxqBlacklistPubIdDto){

        if(StringUtils.isBlank(wxqBlacklistPubIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PUB, wxqBlacklistPubIdDto.getId(), null);
        WxqBlacklistPub wxqBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WxqBlacklistPub.class);
        if(wxqBlacklistPub == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此全网黑名单不存在");
        }

        //是否加入白名单
        String white_id = wxqBlacklistPubIdDto.getMerId() + "_" + wxqBlacklistPub.getWxid();
        Map<String,Object> white_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PUB_WHITE, white_id, null);
        WxqBlacklistPubWhite wxqBlacklistPubWhite  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(white_map)), WxqBlacklistPubWhite.class);
        if(wxqBlacklistPubWhite == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此微信id不存在白名单列表中");
        }

        elasticsearchUtil.deleteDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PUB_WHITE, white_id);

        try {
            //延迟0.5秒
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }

}
